import { defineStore } from 'pinia';

// 默认POI示例数据
const samplePOIs = [
  {
    id: '1',
    name: '西湖无障碍卫生间',
    type: 'toilet',
    details: '门宽90cm，配有扶手，有坡道方便轮椅进入',
    address: '杭州市西湖区龙井路1号附近',
    location: {
      lng: 120.143498,
      lat: 30.242319
    },
    facilityDetails: {
      doorWidth: 90,
      hasRamp: true
    },
    createdAt: new Date(Date.now() - 3600000 * 24 * 3).toISOString(),
    updatedAt: new Date(Date.now() - 3600000 * 24 * 3).toISOString()
  },
  {
    id: '2',
    name: '城市广场无障碍电梯',
    type: 'elevator',
    details: '宽敞的电梯间，轮椅可以方便进出，操作按钮较低',
    address: '杭州市西湖区文一西路98号',
    location: {
      lng: 120.133498,
      lat: 30.232319
    },
    facilityDetails: {
      hasVoicePrompt: true
    },
    createdAt: new Date(Date.now() - 3600000 * 24 * 5).toISOString(),
    updatedAt: new Date(Date.now() - 3600000 * 24 * 5).toISOString()
  },
  {
    id: '3',
    name: '阳光公园爱心停车位',
    type: 'parking',
    details: '靠近公园入口，有明显标识，宽敞好停车',
    address: '杭州市上城区凤凰山路18号',
    location: {
      lng: 120.153498,
      lat: 30.252319
    },
    facilityDetails: {
      count: 3
    },
    createdAt: new Date(Date.now() - 3600000 * 24 * 2).toISOString(),
    updatedAt: new Date(Date.now() - 3600000 * 24 * 2).toISOString()
  }
];

export const usePOIStore = defineStore('poi', {
  state: () => ({
    pois: [], // 存储POI数据
    searchHistory: [], // 搜索历史
    recentViewed: [] // 最近查看
  }),
  
  getters: {
    // 获取所有POI
    getAllPOIs: (state) => {
      return state.pois.sort((a, b) => 
        new Date(b.updatedAt) - new Date(a.updatedAt)
      );
    },
    
    // 根据类型获取POI
    getPOIsByType: (state) => (type) => {
      return state.pois.filter(poi => poi.type === type);
    },
    
    // 根据ID获取POI
    getPOIById: (state) => (id) => {
      return state.pois.find(poi => poi.id === id);
    },
    
    // 获取搜索历史
    getSearchHistory: (state) => {
      return state.searchHistory;
    },
    
    // 获取最近查看
    getRecentViewed: (state) => {
      return state.recentViewed;
    }
  },
  
  actions: {
    // 初始化POI数据
    initPOIs() {
      // 先尝试从存储加载
      this.loadPOIsFromStorage();
      
      // 如果没有数据，加载示例数据
      if (this.pois.length === 0) {
        this.pois = [...samplePOIs];
        this.savePOIsToStorage();
      }
    },
    
    // 添加POI
    addPOI(poiData) {
      try {
        console.log('添加新POI:', poiData);
        
        const newPOI = {
          id: Date.now().toString(), // 使用时间戳作为ID
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          ...poiData
        };
        
        this.pois.push(newPOI);
        this.savePOIsToStorage();
        
        console.log('POI添加成功，当前POI数量:', this.pois.length);
        return newPOI;
      } catch (error) {
        console.error('添加POI失败:', error);
        return null;
      }
    },
    
    // 更新POI
    updatePOI(id, updateData) {
      const index = this.pois.findIndex(poi => poi.id === id);
      if (index !== -1) {
        this.pois[index] = {
          ...this.pois[index],
          ...updateData,
          updatedAt: new Date().toISOString()
        };
        this.savePOIsToStorage();
        return this.pois[index];
      }
      return null;
    },
    
    // 删除POI
    deletePOI(id) {
      const index = this.pois.findIndex(poi => poi.id === id);
      if (index !== -1) {
        this.pois.splice(index, 1);
        this.savePOIsToStorage();
        return true;
      }
      return false;
    },
    
    // 添加搜索历史
    addSearchHistory(keyword) {
      // 避免重复
      const index = this.searchHistory.indexOf(keyword);
      if (index !== -1) {
        this.searchHistory.splice(index, 1);
      }
      
      this.searchHistory.unshift(keyword);
      
      // 控制历史记录数量，最多保留10条
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10);
      }
      
      this.saveSearchHistoryToStorage();
    },
    
    // 清空搜索历史
    clearSearchHistory() {
      this.searchHistory = [];
      this.saveSearchHistoryToStorage();
    },
    
    // 添加最近查看
    addRecentViewed(poiId) {
      const poi = this.getPOIById(poiId);
      if (!poi) return;
      
      // 避免重复
      const index = this.recentViewed.findIndex(item => item.id === poiId);
      if (index !== -1) {
        this.recentViewed.splice(index, 1);
      }
      
      this.recentViewed.unshift({
        id: poi.id,
        name: poi.name,
        type: poi.type,
        viewedAt: new Date().toISOString()
      });
      
      // 控制最近查看数量，最多保留20条
      if (this.recentViewed.length > 20) {
        this.recentViewed = this.recentViewed.slice(0, 20);
      }
      
      this.saveRecentViewedToStorage();
    },
    
    // 从存储加载POI数据
    loadPOIsFromStorage() {
      try {
        const storedPOIs = uni.getStorageSync('customPOIs');
        if (storedPOIs) {
          this.pois = JSON.parse(storedPOIs);
        }
      } catch (e) {
        console.error('加载POI数据失败:', e);
      }
    },
    
    // 保存POI数据到存储
    savePOIsToStorage() {
      try {
        uni.setStorageSync('customPOIs', JSON.stringify(this.pois));
      } catch (e) {
        console.error('保存POI数据失败:', e);
      }
    },
    
    // 加载搜索历史
    loadSearchHistoryFromStorage() {
      try {
        const history = uni.getStorageSync('searchHistory');
        if (history) {
          this.searchHistory = JSON.parse(history);
        }
      } catch (e) {
        console.error('加载搜索历史失败:', e);
      }
    },
    
    // 保存搜索历史
    saveSearchHistoryToStorage() {
      try {
        uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory));
      } catch (e) {
        console.error('保存搜索历史失败:', e);
      }
    },
    
    // 加载最近查看
    loadRecentViewedFromStorage() {
      try {
        const recent = uni.getStorageSync('recentViewed');
        if (recent) {
          this.recentViewed = JSON.parse(recent);
        }
      } catch (e) {
        console.error('加载最近查看失败:', e);
      }
    },
    
    // 保存最近查看
    saveRecentViewedToStorage() {
      try {
        uni.setStorageSync('recentViewed', JSON.stringify(this.recentViewed));
      } catch (e) {
        console.error('保存最近查看失败:', e);
      }
    }
  }
}); 